<template>
  <div class="chart-component">
    <el-card class="chart-card" :class="{ 'edit-mode': isEditMode }">
      <!-- 编辑模式工具栏 -->
      <div v-if="isEditMode" class="component-toolbar">
        <el-button-group size="small">
          <el-button @click="$emit('configure-component', componentConfig)" icon="Setting" circle />
          <el-button @click="$emit('toggle-visibility')" :icon="component.visible ? 'View' : 'Hide'" circle />
          <el-button @click="$emit('remove')" icon="Delete" type="danger" circle />
        </el-button-group>
      </div>

      <!-- 组件标题 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ component.title }}</span>
          <div class="chart-controls">
            <el-select v-model="selectedPeriod" size="small" style="width: 100px">
              <el-option label="7天" value="7d" />
              <el-option label="30天" value="30d" />
              <el-option label="90天" value="90d" />
            </el-select>
            <el-button-group size="small">
              <el-button @click="refreshChart" icon="Refresh" circle />
              <el-button @click="exportChart" icon="Download" circle />
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 图表内容 -->
      <div class="chart-content">
        <div class="chart-container" ref="chartRef"></div>
        
        <!-- 图表说明 -->
        <div class="chart-legend" v-if="config.showLegend !== false">
          <div class="legend-item" v-for="item in legendData" :key="item.name">
            <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
            <span class="legend-name">{{ item.name }}</span>
            <span class="legend-value">{{ item.value }}</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const props = defineProps({
  componentId: {
    type: String,
    required: true
  },
  componentConfig: {
    type: Object,
    default: () => ({})
  },
  isEditMode: {
    type: Boolean,
    default: false
  },
  visible: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['toggle-visibility', 'remove-component', 'configure-component'])

const chartRef = ref()
let chartInstance = null
const selectedPeriod = ref('7d')

const config = computed(() => props.component.config || {})
const chartType = computed(() => config.value.chartType || 'line')

// 图例数据
const legendData = ref([
  { name: '销售额', color: '#409eff', value: '¥128.5万' },
  { name: '利润', color: '#67c23a', value: '¥45.6万' },
  { name: '订单量', color: '#e6a23c', value: '2,340' }
])

// 模拟图表数据
const getChartData = () => {
  const periods = {
    '7d': 7,
    '30d': 30,
    '90d': 90
  }
  
  const days = periods[selectedPeriod.value] || 7
  const dates = []
  const salesData = []
  const profitData = []
  const orderData = []
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }))
    
    // 生成模拟数据
    salesData.push(Math.floor(Math.random() * 50000 + 80000))
    profitData.push(Math.floor(Math.random() * 20000 + 30000))
    orderData.push(Math.floor(Math.random() * 100 + 150))
  }
  
  return { dates, salesData, profitData, orderData }
}

// 获取图表配置
const getChartOption = () => {
  const { dates, salesData, profitData, orderData } = getChartData()
  
  const baseOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        let result = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          const value = param.seriesName === '订单量' 
            ? param.value 
            : `¥${(param.value / 10000).toFixed(1)}万`
          result += `${param.marker}${param.seriesName}: ${value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['销售额', '利润', '订单量'],
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    }
  }
  
  if (chartType.value === 'line') {
    return {
      ...baseOption,
      yAxis: [
        {
          type: 'value',
          name: '金额(万元)',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          axisLabel: {
            color: '#606266',
            formatter: value => `${(value / 10000).toFixed(0)}万`
          }
        },
        {
          type: 'value',
          name: '订单量',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          axisLabel: {
            color: '#606266'
          }
        }
      ],
      series: [
        {
          name: '销售额',
          type: 'line',
          smooth: true,
          data: salesData,
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          }
        },
        {
          name: '利润',
          type: 'line',
          smooth: true,
          data: profitData,
          itemStyle: {
            color: '#67c23a'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ])
          }
        },
        {
          name: '订单量',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: orderData,
          itemStyle: {
            color: '#e6a23c'
          }
        }
      ]
    }
  } else if (chartType.value === 'bar') {
    return {
      ...baseOption,
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#e4e7ed'
          }
        },
        axisLabel: {
          color: '#606266',
          formatter: value => `${(value / 10000).toFixed(0)}万`
        }
      },
      series: [
        {
          name: '销售额',
          type: 'bar',
          data: salesData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#409eff' },
              { offset: 1, color: '#79bbff' }
            ])
          }
        },
        {
          name: '利润',
          type: 'bar',
          data: profitData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#67c23a' },
              { offset: 1, color: '#95d475' }
            ])
          }
        }
      ]
    }
  }
  
  return baseOption
}

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption(getChartOption())
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  }
}

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(getChartOption(), true)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 刷新图表
const refreshChart = () => {
  updateChart()
  ElMessage.success('图表已刷新')
}

// 导出图表
const exportChart = () => {
  if (chartInstance) {
    const url = chartInstance.getDataURL({
      type: 'png',
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.download = `${component.title}_${new Date().toLocaleDateString()}.png`
    link.href = url
    link.click()
    ElMessage.success('图表已导出')
  }
}

// 监听时间周期变化
watch(selectedPeriod, () => {
  updateChart()
})

// 监听图表类型变化
watch(() => config.value.chartType, () => {
  updateChart()
})

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-component {
  position: relative;
}

.chart-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.chart-card.edit-mode {
  border: 2px dashed #409eff;
  position: relative;
}

.chart-card.edit-mode:hover {
  border-color: #67c23a;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.component-toolbar {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  padding: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-content {
  padding: 0;
}

.chart-container {
  width: 100%;
  height: 300px;
  min-height: 300px;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  padding: 16px 0 0 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-name {
  color: #606266;
}

.legend-value {
  font-weight: 600;
  color: #303133;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .chart-controls {
    width: 100%;
    justify-content: space-between;
  }
  
  .chart-container {
    height: 250px;
    min-height: 250px;
  }
  
  .chart-legend {
    flex-direction: column;
    gap: 8px;
    align-items: center;
  }
}
</style>